<template>
    <div ref="threeContainer" class="three-container"></div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

const threeContainer = ref(null);
let scene, camera, renderer, controls, animationFrameId;
 
const initThreeJS = () => {
    // 创建场景
    scene = new THREE.Scene();
 
    // 创建相机
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 5;
 
    // 创建渲染器
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    threeContainer.value.appendChild(renderer.domElement);  // 将渲染器挂载到 DOM 容器
 
    // 添加一个立方体
    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
 
    // 添加相机控制--鼠标拖拽旋转
    controls = new OrbitControls(camera, renderer.domElement);
 
    // 动画循环
    const animate = () => {
        animationFrameId = requestAnimationFrame(animate);
        cube.rotation.x += 0.01;  // 旋转立方体
        cube.rotation.y += 0.01;
        renderer.render(scene, camera);  // 渲染场景
    };
    animate();
};
// 监听窗口大小变化事件，动态调整相机和渲染器尺寸
const onWindowResize = () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
};
// 初始化 Three.js 场景
onMounted(() => {
    initThreeJS();
    window.addEventListener('resize', onWindowResize);
});
// 清理资源，避免内存泄漏
onBeforeUnmount(() => {
    cancelAnimationFrame(animationFrameId);  // 取消动画循环
    window.removeEventListener('resize', onWindowResize); // 移除事件监听
    renderer.dispose(); // 释放渲染器资源
});
</script>

<style lang="less" scoped>
.three-container {
    width: 100%;
    height: 100vh;
    overflow: hidden;
}
</style>